package dhm.com.hpx.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import dhm.com.hpx.R;
import dhm.com.hpx.activity.ArticleActivity;
import dhm.com.hpx.activity.PosterActivity;
import dhm.com.hpx.activity.VideoActivity;
import dhm.com.hpx.adapter.MainArticleAdapter;
import dhm.com.hpx.adapter.MainPosterAdapter;
import dhm.com.hpx.adapter.MainVideoAdapter;
import dhm.com.hpx.base.BaseFragment;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.MainArticleBean;
import dhm.com.hpx.entity.MainPosterBean;
import dhm.com.hpx.entity.MainVideoBean;
import dhm.com.hpx.utils.SpUtils;

/**
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class ShopHomeFragment extends BaseFragment implements LoginContract.IView {

    @BindView(R.id.recy)
    XRecyclerView recy;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;

    private int industry_id;

    private View rootView;
    private PressenterImpl pressenter;
    private String uid;
    private MainArticleAdapter mainArticleAdapter;
    private List<MainArticleBean.DataBean> mainArticleBeanData;
    private List<MainVideoBean.DataBean> mainVideoBeanData;
    private MainVideoAdapter mainVideoAdapter;
    private List<MainPosterBean.DataBean> mainPosterBeanData;
    private MainPosterAdapter mainPosterAdapter;

    @Override
    protected int getLayout() {
        return R.layout.shop_fragment;
    }

    private String type;
    private int page = 1;

    public ShopHomeFragment(int industry_id, String type) {
        this.industry_id = industry_id;
        this.type = type;
    }

    @Override
    protected void initView() {
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
        uid = SpUtils.getString(getActivity(), "uid");

//        recy.setLoadingMoreEnabled(true);
//        recy.setPullRefreshEnabled(true);



        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page=1;
                getdata();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                getdata();
            }
        });


/*
        recy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getdata();
            }

            @Override
            public void onLoadMore() {
                getdata();
            }
        });
*/
        page=1;


        initData();

    }

    private void getdata() {
        Map<String, String> map;
        if (industry_id == 0) {
//1文章，2视频，3海报
            switch (type) {
                case "1":
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    pressenter.sendMessage(getActivity(), Constant.article_list, map, MainArticleBean.class);
                    break;
                case "2":
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    pressenter.sendMessage(getActivity(), Constant.videovideo_list, new HashMap<String, String>(), MainVideoBean.class);
                    break;
                case "3":
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    pressenter.sendMessage(getActivity(), Constant.posterposter_list, new HashMap<String, String>(), MainPosterBean.class);
                    break;
                default:
            }
        } else {
//1文章，2视频，3海报
            switch (type) {
                case "1":
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    map.put("industry_id", industry_id + "");
                    pressenter.sendMessage(getActivity(), Constant.article_list, map, MainArticleBean.class);
                    break;
                case "2":
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    map.put("industry_id", industry_id + "");
                    pressenter.sendMessage(getActivity(), Constant.videovideo_list, new HashMap<String, String>(), MainVideoBean.class);
                    break;
                case "3":
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid", uid);
                    map.put("page", page + "");
                    map.put("industry_id", industry_id + "");
                    pressenter.sendMessage(getActivity(), Constant.posterposter_list, new HashMap<String, String>(), MainPosterBean.class);
                    break;
                default:
            }
        }


    }

    @Override
    protected void initData() {
        getdata();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.shop_fragment, container, false);
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void requesta(Object data) {
        if (data instanceof MainArticleBean) {
            final MainArticleBean mainArticleBean = (MainArticleBean) data;
            if (mainArticleBean.getCode() == 1) {
                if (page==1){
                    recy.setVisibility(View.VISIBLE);
                    LinearLayoutManager manager = new LinearLayoutManager(getActivity());
                    manager.setOrientation(LinearLayoutManager.VERTICAL);
                    recy.setLayoutManager(manager);
                    mainArticleBeanData = mainArticleBean.getData();

                    mainArticleAdapter = new MainArticleAdapter(getActivity());

                    mainArticleAdapter.setdeleteClick(new MainArticleAdapter.OnClick() {
                        @Override
                        public void item(int posttion) {
                            Intent intent = new Intent(getActivity(), ArticleActivity.class);
                            intent.putExtra("article_id", mainArticleBean.getData().get(posttion).getId() + "");
                            intent.putExtra("coverImg",mainArticleBean.getData().get(posttion).getCoverImg()+"");
                            getActivity().startActivity(intent);

                        }
                    });

                    recy.setAdapter(mainArticleAdapter);

                    recy.addOnScrollListener(new RecyclerView.OnScrollListener() {
                        @Override
                        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                            super.onScrollStateChanged(recyclerView, newState);
                            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                                if (!isUserControl) {
                                    recy.postDelayed(thread, 200);
                                }
                            }
                            if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_SETTLING) {//非自动滑动
                                isUserControl = false;
                            }
                        }

                        @Override
                        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                            super.onScrolled(recyclerView, dx, dy);
                            if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_SETTLING && !isUserControl) {
                                if (-3<dy&&dy<3) {//向下滚动
                                    recyclerView.stopScroll();
                                }
                            }
                        }
                    });


                }else {
                    mainArticleBeanData.addAll(mainArticleBean.getData());
                }
                mainArticleAdapter.setList(mainArticleBeanData);
                page++;
            } else {
                if (page==1){
                    recy.setVisibility(View.GONE);
                }
                Toast.makeText(getActivity(), mainArticleBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else if (data instanceof MainVideoBean) {
            final MainVideoBean mainVideoBean = (MainVideoBean) data;
            if (mainVideoBean.getCode() == 1) {
                if (page==1){
                    GridLayoutManager manager=new GridLayoutManager(getActivity(),2);
                    manager.setOrientation(LinearLayoutManager.VERTICAL);
                    recy.setLayoutManager(manager);
                    mainVideoBeanData = mainVideoBean.getData();
                    recy.setVisibility(View.VISIBLE);

                    mainVideoAdapter = new MainVideoAdapter(getActivity());
                    mainVideoAdapter.setdeleteClick(new MainVideoAdapter.OnClick() {
                        @Override
                        public void item(int posttion) {
                            Intent intent = new Intent(getActivity(), VideoActivity.class);
                            intent.putExtra("video_id", mainVideoBean.getData().get(posttion).getId() + "");
                            intent.putExtra("coverImg",mainVideoBean.getData().get(posttion).getCoverImg()+"");
                            getActivity().startActivity(intent);
                        }
                    });
                    recy.setAdapter(mainVideoAdapter);
                }else {
                    mainVideoBeanData.addAll(mainVideoBean.getData());
                }
                mainVideoAdapter.setList(mainVideoBeanData);
                page++;

            } else {
                if (page==1){
                    recy.setVisibility(View.GONE);
                }
                Toast.makeText(getActivity(), mainVideoBean.getMessage(), Toast.LENGTH_SHORT).show();
            }


        } else if (data instanceof MainPosterBean) {
            final MainPosterBean mainPosterBean = (MainPosterBean) data;
            if (mainPosterBean.getCode() == 1) {
                if (page==1){
                    GridLayoutManager manager = new GridLayoutManager(getActivity(),2);
                    manager.setOrientation(LinearLayoutManager.VERTICAL);
                    recy.setLayoutManager(manager);
                    recy.setVisibility(View.VISIBLE);
                    mainPosterBeanData = mainPosterBean.getData();

                    mainPosterAdapter = new MainPosterAdapter(getActivity());

                    mainPosterAdapter.setdeleteClick(new MainPosterAdapter.OnClick() {
                        @Override
                        public void item(int posttion) {
                            Intent intent = new Intent(getActivity(), PosterActivity.class);
                            intent.putExtra("poster_id", mainPosterBean.getData().get(posttion).getId() + "");
                            getActivity().startActivity(intent);
                        }
                    });

                    recy.setAdapter(mainPosterAdapter);
                }else {
                    mainPosterBeanData.addAll(mainPosterBean.getData());
                }
                mainPosterAdapter.setList(mainPosterBeanData);
                page++;

            } else {
                if (page==1){
                    recy.setVisibility(View.GONE);
                }
                Toast.makeText(getActivity(), mainPosterBean.getMessage(), Toast.LENGTH_SHORT).show();
            }


        }
      /*  recy.refreshComplete();
        recy.loadMoreComplete();*/
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void fail(String error) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private boolean isUserControl = false;
    private void smoothScrollToPosition() {
        isUserControl = true;
        View stickyInfoView = recy.getChildAt(0);
        int bottom = stickyInfoView.getBottom();
        int height = stickyInfoView.getMeasuredHeight();
        if (bottom != height) {
            if (bottom >= (height / 2)) {
                recy.smoothScrollBy(0, -(height - bottom));
            }else {
                recy.smoothScrollBy(0, bottom);//二次滑动
            }
        }


    }

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            smoothScrollToPosition();
        }
    });



}
